package com.sky.business.sys.handler.endpoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.business.sys.domain.CameraConfig;
import com.sky.business.sys.domain.SystemConfig;
import com.sky.business.sys.event.DeviceMetadata;
import com.sky.business.sys.event.endpoint.CameraInfoRequestEvent;
import com.sky.business.sys.event.endpoint.CameraInfoResponseEvent;
import com.sky.business.sys.event.endpoint.DeviceInfoDto;
import com.sky.business.sys.handler.MqttEventHandler;
import com.sky.business.sys.service.CameraConfigService;
import com.sky.business.sys.service.SystemConfigService;
import com.sky.business.sys.util.MQTTClientUtils;
import com.sky.common.config.CacheConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.SimpleTimeZone;

/**
 * 终端请求设备信息处理器
 *
 */
@Component
public class CameraInfoRequestEventHandler implements MqttEventHandler {

    @Autowired
    private CameraConfigService cameraConfigService;

    @Autowired
    private SystemConfigService systemConfigService;

    public static final ObjectMapper objectMapper = new ObjectMapper().setTimeZone(SimpleTimeZone.getTimeZone("GMT+8"));

    @Override
    public boolean match(String topic, String msg,String event) {
        return "CameraInfoRequest".equals(event);
    }

    @Override
    public void handle(String topic, String msg) throws Exception {
        CameraInfoRequestEvent cameraInfoRequestEvent = objectMapper.readValue(msg, CameraInfoRequestEvent.class);
        DeviceMetadata metadata = cameraInfoRequestEvent.getMetadata();
        SystemConfig systemConfig = systemConfigService.getSystemConfig();
        CameraConfig cameraConfig = cameraConfigService.findByDeviceId(metadata.getDeviceId());
        CameraInfoResponseEvent cameraInfoResponseEvent;
        if (cameraConfig != null) {
            DeviceInfoDto deviceInfoDto = DeviceInfoDto.valueOf(cameraConfig, systemConfig);
            cameraInfoResponseEvent = new CameraInfoResponseEvent(systemConfig.getEdgeId(), metadata.getDeviceId(), deviceInfoDto, CacheConstants.CODE_STATUS_OK, "");
        } else {
            cameraInfoResponseEvent = new CameraInfoResponseEvent(systemConfig.getEdgeId(), metadata.getDeviceId(), null, CacheConstants.CODE_STATUS_ERROR, "设备不存在");
        }
        String responseMsg = objectMapper.writeValueAsString(cameraInfoResponseEvent);
        MQTTClientUtils.publish(MQTTClientUtils.LOCAL_MQTT_CLIENT, cameraConfig.getDispatcherTopic(), CacheConstants.DEFAULT_QOS, responseMsg);
    }


}
